//
//  SEGChooseRentalHouseViewController.m
//  ExcellentHome
//
//  Created by 陈区 on 13-11-22.
//  Copyright (c) 2013年 陈区. All rights reserved.
//
#import "SEGChooseRentalHouseViewController.h"
@interface SEGChooseRentalHouseViewController ()

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, assign) NSInteger selectIndex; //选中的index

@end

@implementation SEGChooseRentalHouseViewController


- (id)initWithNibName:(NSString*)nibNameOrNil bundle:(NSBundle*)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.title = @"选择房屋";
    [self showCustomNavigationBackButton];
    [self setupUI];
    
    self.selectIndex = [[self.params objectForKey:@"index"] longValue];
    
    SEGProfileModel *account = [SEGProfileManager sharedManager].profile;
    self.listData = account.houseList;
}

- (void)setupUI {
    self.view.backgroundColor = kColor_bg;
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.dataSource = self;
    self.tableView.backgroundView = nil;
    self.tableView.estimatedRowHeight = 44;
    self.tableView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:self.tableView];
    
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.mas_equalTo(0);
        make.top.mas_equalTo(0);
    }];
}

// 请求房屋列表
- (void)requestHouseList {
    NSString *urlString = [SEGServerManager serverUrlJoint:kClientRootURL,@"/enterprise-app/base/selectHouse",nil];
    SEGQueryauthinfoDataModel *data = [SEGQueryauthinfoManager sharedManager].QueryAuthInfo.data;
    NSDictionary *param = @{@"communityId"  : kAccountCommunityID,
                            @"enterpriseId" : data.userInfo.enterpriseId ?: @""
                            };
    
    [SEGHTTPBusinessManager seg_requestWithMethod:GET URLString:urlString parameters:param finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
        if (isSuccessed) {
            
            NSMutableArray *tempArray = [NSMutableArray array];
            for (NSDictionary *subDic in result[@"data"][@"data"]) {
                SEGProfileHouselistModel *model = [SEGProfileHouselistModel yy_modelWithDictionary:subDic];
                [tempArray addObject:model];
            }
            self.listData = [tempArray copy];
            [self.tableView reloadData];
        } else {
            [SEGAlertView showTmepMessageWithMessage:errorMessage];
        }
        if (self.listData.count == 0) {
            [[SEGUhomeMediator sharedInstance] seg_showCustomProgressImage:@{@"view":self.tableView, @"text":@"暂无房屋", kNoDataOriginY:@(0)}];
        }
    }];
}

#pragma mark - tableview datasource
- (NSInteger)numberOfSectionsInTableView:(UITableView*)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section
{

    return [self.listData count];
}

//每行的高度
- (CGFloat)tableView:(UITableView*)tableView heightForRowAtIndexPath:(NSIndexPath*)indexPath
{

    return UITableViewAutomaticDimension;
}

- (UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath
{
    NSString* indentSt = @"wbcell"; // [NSString stringWithFormat:@"cell %d %d",indexPath.section,indexPath.row];

    SEGBaseTableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:indentSt];

    if (cell == nil) {
        cell = [[SEGBaseTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:indentSt];

        cell.accessoryType = UITableViewCellAccessoryNone;
        cell.backgroundColor = [UIColor whiteColor];

        UILabel* leftLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 0, CGRectGetWidth(self.view.bounds)-61, 44)];
        [leftLabel setTextColor:kColor_2];
        [leftLabel setText:@" "];
        leftLabel.numberOfLines = 0;
        leftLabel.tag = 1010;
        leftLabel.font = [UIFont systemFontOfSize:FONT_LIST_AND_DETAIL_SIZE];
        [leftLabel setBackgroundColor:[UIColor clearColor]];
        [cell.contentView addSubview:leftLabel];
        
        UIImageView *selectImageView = [UIImageView new];
        selectImageView.tag = 2000;
        
        selectImageView.image = [[UIImage imageWithContentsOfFile:SEGPicName(@"check_small.png")] imageByTintColor:kColor_T];
        [cell.contentView addSubview:selectImageView];

        UIImageView* lineImgView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 43, tableView.frame.size.width, 0.5)];
        lineImgView.tag = 999;
        lineImgView.backgroundColor = kColor_L2;
        [cell.contentView addSubview:lineImgView];
    }
    UIImageView* checkBox = [cell.contentView viewWithTag:2000];

    SEGProfileHouselistModel* entity = [self.listData objectAtIndex:indexPath.row];
    UILabel* view = (UILabel*)[cell viewWithTag:1010];
    if (view) {
        NSString* cellTextStr = entity.fullHouseName;
        [view setText:cellTextStr];
    }
    [view mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(cell.contentView).offset(20);
        make.right.equalTo(cell.contentView).offset(-61);
        make.top.equalTo(cell.contentView).offset(5);
        make.bottom.equalTo(cell.contentView).offset(-5);
        make.height.mas_greaterThanOrEqualTo(34);
    }];
    
    [checkBox mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(cell.contentView);
        make.size.mas_equalTo(CGSizeMake(11, 8));
        make.right.equalTo(cell.contentView).offset(-20);
    }];
    UIView *lineView = [cell.contentView viewWithTag:999];
    [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(cell.contentView);
        make.height.mas_equalTo(0.5);
    }];

    // 如果有设置selectHouseID则根据其进行判断，否则就根据之前的self.selectIndex判断。
    if (self.selectHouseID != nil && self.selectHouseID.length != 0) {
        checkBox.hidden = ![entity.houseId isEqualToString:self.selectHouseID];
    } else {
        checkBox.hidden = indexPath.row != self.selectIndex;
    }

    return cell;
}

#pragma mark - tableview delegate

- (void)tableView:(UITableView*)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath
{
    self.selectIndex = indexPath.row;
    SEGProfileHouselistModel* entity = [self.listData objectAtIndex:indexPath.row];
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (self.isServiceAppointment) {
        if (self.chooseRentalHouseDelegate && [self.chooseRentalHouseDelegate respondsToSelector:@selector(selectHouseType:withHouseId:withKey:)]) {
            [self.chooseRentalHouseDelegate selectHouseType:entity.fullHouseName withHouseId:entity.houseId withKey:self.modelKey];
        }
    }
    else if (self.house) {
        if (self.chooseRentalHouseDelegate && [self.chooseRentalHouseDelegate respondsToSelector:@selector(selectRentalHouseType:withHouseId:withCommunity:)]) {
            [self.chooseRentalHouseDelegate selectRentalHouseType:entity.houseName withHouseId:entity.houseId withCommunity:entity.communityName];
        }
    }
    [self.navigationController popViewControllerAnimated:YES];
}


@end
